package com.example.financialsystem;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import models.ClassifiedInfo;
import models.StandardStatisticData;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import others.ServerResponse;

import static others.Const.IP;
import static others.Const.PORT;
import static others.Const.currentBook;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;
import static utils.GsonUtil.String2ListClassifiedServerResponse;

public class ChartActivity extends AppCompatActivity {

    @BindView(R.id.myChart)
    PieChart mPieChart;
    @BindView(R.id.chart_inOrOut)
    Spinner spinnerConsumeType;
    @BindView(R.id.chart_timeZone)
    Spinner spinnerTimeZone;

    private int consumeType = 0;
    private int timeZone = 0;

    private Request request;
    private String responseData;

    public final static int GETChartData = 1;
    Hashtable<String, Double> inHashTable = new Hashtable<>();
    Hashtable<String, Double> outHashTable = new Hashtable<>();
    List<StandardStatisticData> standardDataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);
        ButterKnife.bind(this);

        //饼状图
        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);

        mPieChart.setDragDecelerationFrictionCoef(0.95f);
        //设置中间文件
        mPieChart.setCenterText("财务统计");

        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);

        mPieChart.setHoleRadius(58f);
        mPieChart.setTransparentCircleRadius(61f);

        mPieChart.setDrawCenterText(true);

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        //变化监听
        mPieChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                //h.getY()
            }

            @Override
            public void onNothingSelected() {

            }
        });

        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.WHITE);
        mPieChart.setEntryLabelTextSize(12f);

        mPieChart.animateXY(1400, 1400);

        spinnerConsumeType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                consumeType = position;
                if (consumeType == 0) {
                    constructStandardData(outHashTable);
                } else if (position == 1){
                    constructStandardData(inHashTable);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinnerTimeZone.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                timeZone = position;
                request = constructRequest(timeZone);
                sendRequest(request);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        request = constructRequest(timeZone);
        sendRequest(request);
    }

    public void loadData(){
        //模拟数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        for (int i = 0 ; i<standardDataList.size() ; i++){
            entries.add(new PieEntry((float)standardDataList.get(i).getPercentage(),standardDataList.get(i).getName()));
        }
        //设置数据
        setData(entries);
    }

    //设置数据
    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "图例");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);

        //刷新
        mPieChart.invalidate();
    }

    public Request constructRequest(int timeZone){
        String url = "http://" + IP + ":" + PORT + "/portal/classifiedStatistics.do";
        RequestBody requestBody = new FormBody.Builder()
                .add("bookId",currentBook.getId())
                .add("timeZoneType",timeZone+"")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return request;
    }

    public void sendRequest(Request request){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Response response = client.newCall(request).execute();
                    responseData = response.body().string();
                    Message message = new Message();
                    message.what = GETChartData;
                    handler.sendMessage(message);
                } catch (Exception e){
                    e.printStackTrace();
                    ToastShow("我们可能遭遇了一些麻烦1(ChartActivity)");
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case GETChartData:
                    Log.d("test", responseData);
                    ServerResponse<ClassifiedInfo> serverResponse
                            = String2ListClassifiedServerResponse(responseData);
                    if (serverResponse.getStatus() == 0){
                        inHashTable = serverResponse.getData().getInHashTable();
                        outHashTable = serverResponse.getData().getOutHashTable();
                        if (consumeType == 0){
                            constructStandardData(outHashTable);
                        } else {
                            constructStandardData(inHashTable);
                        }
                    }else {
                        ToastShow("我们可能遭遇了一些麻烦2(ChartActivity)");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public void constructStandardData(Hashtable<String,Double> hashtable){
        float totalMoney = 0;
        standardDataList.clear();
        for(Map.Entry<String,Double> entry: hashtable.entrySet()){
            StandardStatisticData newData = new StandardStatisticData(entry.getKey(),entry.getValue(),0);
            totalMoney += entry.getValue();
            standardDataList.add(newData);
        }
        for (int i=0;i<standardDataList.size();i++){
            standardDataList.get(i).setPercentage(standardDataList.get(i).getMoney()/totalMoney);
        }
        if (standardDataList.size() == 0){
            mPieChart.setVisibility(View.GONE);
            ToastShow("暂时没有数据");
        } else {
            mPieChart.setVisibility(View.VISIBLE);
            loadData();
        }
    }
}
